
	var url_notes = "/admin/process/zTreeRole.html";//获取url 
	var url_applySave = "/admin/process/applySave.html";




	var multi = true ;  // 多选true 单选false

	//全局变量
	var zTree = null; //zTree对象
	var zNodes = [];  //数据
	var roles = [];

	

	//ztree 配置
	var setting = {
		check: {
				enable: true,
				chkStyle: multi ? "checkbox" : "radio" ,
				radioType: "all"

			},

		view: {
			dblClickExpand: false,  //双击展开
			showLine: true,        //是否显示 连接线
			selectedMulti: multi,   //设置是否允许同时选中多个节点。默认值: true
			//showIcon:true , //是否显示图标
		},
		data: {
			key:{
				name: "name",
			},
			simpleData: {
				enable:true, 
				idKey: "id",
				pIdKey: "pid",
				rootPId: ""
			},
			

		},
		callback: {
			beforeClick:beforeClick, 
			onClick:onClick,
	        onExpand: onExpand,  // 展开
	        onCollapse: onCollapse,  // 折叠  
	        onCheck: zTreeOnCheck,

		}
	};


	// zTree展开 回调函数
    function onExpand(event, treeId, treeNode){  
        var cookie = $.cookie("z_tree");  
          
        var z_tree = null;  
        if(cookie){  
            z_tree = JSON.parse(cookie);  
        }  
          
        if(!z_tree){  
            z_tree = new Array();  
        }  
        if(jQuery.inArray(treeNode.id, z_tree)<0){  
            z_tree.push(treeNode.id); //追加 
        }  
          
          
        $.cookie("z_tree", JSON.stringify(z_tree))  
    }  


    // zTree折叠   回调函数
    function onCollapse(event, treeId, treeNode){  
        var cookie = $.cookie("z_tree");  
          
        var z_tree = null;  
        if(cookie){  
            z_tree = JSON.parse(cookie);  
        }  
          
        if(!z_tree){  
            z_tree = new Array();  
        }  
        var index = jQuery.inArray(treeNode.id, z_tree);  
          
        z_tree.splice(index, 1); //删除  
          
        $.cookie("z_tree", JSON.stringify(z_tree))  
    }

    //zTree
    function beforeClick(treeId, treeNode, clickFlag) {
		// console.log('beforeClick:' ,treeNode , clickFlag);

		zTree.checkNode( treeNode , true, true); //设置被选中

		zTree_setCheckNodeSelected();
		// return (treeNode.checked );
		return false;
		
	}
	function zTreeOnCheck(event, treeId, treeNode) {
	    zTree_setCheckNodeSelected();
	};

	//设置 check node  select
	function zTree_setCheckNodeSelected()
	{

		console.log('zTree_setCheckNodeSelected : 设置选中的 文字 选中');
		var nodes = getCheckedNodes();//获取选中的节点 

		console.log(nodes);

		zTree.cancelSelectedNode();

		for(var i = 0 ,len = nodes.length ; i< len ; i++){
			zTree.selectNode(nodes[i], !!i  ); //第二参数 i  , 第一次false 之后都是true
 		} 
	}

	//获取选中节点  zTree.getCheckedNodes(true); 获取的包含 半选中  需要过滤
	function getCheckedNodes(){
		var nodes = zTree.getCheckedNodes(true);//获取选中的节点  全勾 半勾
		var node2 = [];
		for(var i = 0 ,len = nodes.length ; i< len ; i++){
			//过滤掉 半勾的
			if( ! nodes[i].getCheckStatus().half ){ node2.push(nodes[i]); }
			
 		} 
 		return node2;

	}

	function onClick(event, treeId, treeNode, clickFlag){
	
	}

	//设置选中  by id
	function zTree_setCheckNodeById( ids = null){
		console.log('zTree_setCheckNodeById: id =' , ids );

		if(!ids){return false;}
		var ids = ids.split(",");

		console.log(ids);
		for( var i = 0, len = ids.length ; i < len ; i ++){
			var treeNode  = zTree.getNodeByParam("id", ids[i], null);
			zTree.checkNode( treeNode , true, true); //设置被选中
		}
		zTree_setCheckNodeSelected()


		// var treeNode  = zTree.getNodeByParam("id", id, null);

		// zTree.checkNode( treeNode , true, true); //设置被选中
		// zTree_setCheckNodeSelected()
	}
	//
	function zTree_init(){
		console.log('zTree_init');

		//jBox.tip('loading...' , 'loading');
	    $.ajax({
	        type:'post',
	        url:url_notes,
	        data: {process_id:process_id},
	        dataType:'json',
	        success:function(d){

	        		//jBox.closeTip();
	        		zNodes = d.zNodes;
	        		roles = d.roles;
	        		zTree_create();

	        		console.log(d.roles);

	        		zTree_setCheckNodeById( roles );

	        },
	        error:function(a,b,c){
	            jBox.tip('ajax error：' + b );
	        }
	    });

	}


	//
	function zTree_create(){
			
		zTree = $.fn.zTree.init($('#ztree_apply'), setting, zNodes);
		//根据cookie 展开 ztree
		var cookie = $.cookie("z_tree");  
	    if(cookie){  
	        z_tree = JSON.parse(cookie);  
	        for(var i=0; i< z_tree.length; i++){  
		        var node = zTree.getNodeByParam('id', z_tree[i])  
		        zTree.expandNode(node, true)  
	        }  
	    }  
	}

	//展开折叠切换
	var flag_expand = false;
	function expandAll(obj){
		if(! $(obj).length ) return false ;
		var z_tree = [];

		if( flag_expand ){
			$(obj).text(' 展开');
			//z_tree = [];

		}else{
			$(obj).text(' 折叠');
			for(var i = 0 , len = zNodes.length ; i < len  ;  i++  ){
				z_tree.push( zNodes[i].id );
			}
		}

		$.cookie("z_tree", JSON.stringify(z_tree));
		zTree.expandAll(flag_expand = !flag_expand);
		// var node = zTree.getNodeByParam("id", 5);
		// zTree.selectNode(node, true, true);
		// zTree.checkNode(node, true, true);

	}
	//创建ztree；
	zTree_init();


	//获取选中的 岗位 的 ids 
	function getRoleIds(){
		console.log('getRoleIds:');
		var ids = [];
		var nodes = getCheckedNodes();
		var id ;

		for(var i = 0 ,len = nodes.length ; i < len ; i++ ){
			id = nodes[i].id.toString() ;
			ids.push(  id   ) ;

		}
		return ids.join(',');
	}
    

    $(function(){
    	$('#saveSubmit').on('click',function(){
    		var ids = getRoleIds();
    		//a = str.split("a").join("");
    		jBox.tip( '提交中...', 'loading');
    		$.ajax({
                url: url_applySave ,
                type:"post" , // get post
                data: {process_id:process_id , ids:ids} , 
                dataType : 'html' ,
                success:function(d){
                    try{d = JSON.parse(d);}catch(err){jBox.alert( d , '查看ajax返回值');return false;}
                    if( 1 == d.code){
                        jBox.tip( d.msg , 'success');
                        setTimeout(function(){layer_close(1);},1000);
                    }else{
                        jBox.tip( d.msg , 'error');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){
                    console.log( 'ajaxError : ' + textStatus );
                },
                complete:function(){
                    setTimeout(function(){jBox.closeTip();},3000);
                }
            });
    	});

	})	


